package com.macasa.panel.web.auth.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.ProviderNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.macasa.panel.common.log.Logger;
import com.macasa.panel.entity.api.IUser;
import com.macasa.panel.exception.DALException;
import com.macasa.service.dal.api.IUserDal;

/*
 * Spring-security requires an implementation of UserDetailService.
 */
@Service("userDetailsService")
@Scope("singleton")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	@Qualifier("userDal")
	private IUserDal	userDal;

	@Override
	public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

		try {
			final IUser u = this.userDal.getUserByLogin(username);
			if (u != null) {

				final Collection<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
				grantedAuthorities.add(new SimpleGrantedAuthority(u.getCurrentRole().getName())); // RoleName = "ROLE_ADMIN" or "ROLE_REGISTERED"

				final org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(u.getLogin(),
						u.getPassword(), u.isEnabled(), u.isAccountNonExpired(), u.isCredentialsNonExpired(), u.isAccountNonLocked(), grantedAuthorities);

				return user;
			} else {

				throw new UsernameNotFoundException("No such user");
			}
		} catch (final DALException e) {
			Logger.error("getUserByLogin failed", e);
			throw new ProviderNotFoundException("User dal failed");
		}

	}

	/**
	 * @param userDal
	 *            the userDal to set
	 */
	public final void setUserDal(final IUserDal userDal) {
		this.userDal = userDal;
	}
}
